package com.iflytek.uoamp.agent.monitor.mcagent;

import com.iflytek.uoamp.agent.common.util.WFile;
import com.iflytek.uoamp.agent.core.sender.monitorsender.requestObj.DownloadAgentPackage;
import com.iflytek.uoamp.agent.core.sender.monitorsender.responseObj.AutoPluginFile;
import com.iflytek.uoamp.agent.monitor.find.CMDExextor;

import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 
 * @ClassName: AgentUpdateThread
 * @Description: agent版本更新
 * @author qinanyuan
 * @date 2017年3月23日 下午3:19:53
 */
public class AgentUpdateThread extends Thread {	

	public AgentUpdateThread(Map<String,String> result ,String localVersion){
		this.result = result;
		this.setLocalVersion(localVersion);
	}
    
	private Map<String,String> result;
	
	private String localVersion;
	
	public String getLocalVersion() {
		return localVersion;
	}

	public void setLocalVersion(String localVersion) {
		this.localVersion = localVersion;
	}
	
	
	@SuppressWarnings("rawtypes")
	@Override
	public void run() {
		//获取当前jar包版本号
		String newVersion="";
		Set keys = result.keySet();
		if(keys != null) {
		    Iterator iterator = keys.iterator();
		    while(iterator.hasNext()) {
		    	newVersion = iterator.next().toString();
		    }
		}
        //写入新的版本号到"conf/version",防止新版本下载更新的时候不会出现重复创建agent更新线程
        WFile.wf("conf/version",newVersion ,"utf-8",false);
    	//判断是否复制成功
        boolean mainCopySuc = false;
        boolean coreCopySuc = false;
        boolean commonCopySuc = false;
        boolean loggerCopySuc = false;
        boolean monitorCopySuc = false;
        boolean copysuc = true;
    	boolean isLinux = MCAgentConfig.getInstance().isLinux();
        try {
        	DownloadAgentPackage downloadAgentPackage = new DownloadAgentPackage();
        	AutoPluginFile agentFile = (AutoPluginFile) MCAgentMain.getSenderClient().sendBySafe(downloadAgentPackage);
        	File file = new File("");
        	String dir = file.getAbsolutePath();
        	String filenameCpl = agentFile.getFilename();
        	String filename = filenameCpl.split(".zip")[0];
        	//写入本地
        	if(WFile.wfByByte(dir + "/upload/agentzip/"+filenameCpl, agentFile.getFilebyte())){
        		Logger.getRootLogger().info("upload file " + filenameCpl + " success!");
        		//解压下载的zip文件
        		WFile.unZipFiles(dir + "/upload/agentzip/" + filenameCpl, dir + "/upload/agentzip/", isLinux);
        		String unzipFilePath = dir + "/upload/agentzip/" + filename;
        		Logger.getRootLogger().info("unzipFile: " + unzipFilePath + " success!");
        		File unzipFilePathFile = new File(unzipFilePath);
        		if(unzipFilePathFile.exists()){

        			String srcDir = dir.concat("/upload/agentzip/").concat(filename).concat("/");
        			String dstDir = dir.concat("/");

                    //将解压的uoamp-agent-main-0.0.1-SNAPSHOT.jar复制到根目录下并命名为uoamp-agent-main.new.jar
        			String mainSrcFilePath = srcDir.concat("uoamp-agent-main-0.0.1-SNAPSHOT.jar");
        			String mainDstFilePath = dstDir.concat("uoamp-agent-main.new.jar");
                    //如果根目录下有uoamp-agent-main.new.jar则删除
        			File mainFile = new File(mainSrcFilePath);
        			if(mainFile.exists()){
        				File oldMainFile = new File(mainDstFilePath);
        				if(oldMainFile.exists()){
        					oldMainFile.delete();
        				}
        				mainCopySuc = WFile.copyFile(mainSrcFilePath, mainDstFilePath);
        				copysuc = copysuc && mainCopySuc;
        				Logger.getRootLogger().info("copyFile " + mainSrcFilePath +" result -->".concat(String.valueOf(mainCopySuc)));
        			}

                    //将解压的uoamp-agent-monitor-0.0.1-SNAPSHOT.jar复制到根目录下并命名为uoamp-agent-monitor.new.jar
                    String monitorSrcFilePath = srcDir.concat("lib/uoamp-agent-monitor-0.0.1-SNAPSHOT.jar");
                    String monitorDstFilePath = dstDir.concat("lib/uoamp-agent-monitor.new.jar");
                    //如果根目录下有uoamp-agent-monitor.new.jar则删除
                    File monitorFile = new File(monitorSrcFilePath);
                    if(monitorFile.exists()){
                    	File oldMonitorFile = new File(monitorDstFilePath);
                    	if(oldMonitorFile.exists()){
                    		oldMonitorFile.delete();
                    	}
                    	monitorCopySuc = WFile.copyFile(monitorSrcFilePath, monitorDstFilePath);
                    	copysuc = copysuc && monitorCopySuc;
                    	Logger.getRootLogger().info("copyFile " + monitorSrcFilePath +" result -->".concat(String.valueOf(monitorCopySuc)));
                    }

                    //将解压的uoamp-agent-core-0.0.1-SNAPSHOT.jar复制到根目录下并命名为uoamp-agent-core.new.jar
                    String coreSrcFilePath = srcDir.concat("lib/uoamp-agent-core-0.0.1-SNAPSHOT.jar");
                    String coreDstFilePath = dstDir.concat("lib/uoamp-agent-core.new.jar");
                    //如果根目录下有uoamp-agent-core.new.jar则删除
                    File coreFile = new File(coreSrcFilePath);
                    if(coreFile.exists()){
                    	File oldCoreFile = new File(coreDstFilePath);
                    	if(oldCoreFile.exists()){
                    		oldCoreFile.delete();
                    	}
                    	coreCopySuc = WFile.copyFile(coreSrcFilePath, coreDstFilePath);
                    	copysuc = copysuc && coreCopySuc;
                    	Logger.getRootLogger().info("copyFile " + coreSrcFilePath +" result -->".concat(String.valueOf(coreCopySuc)));
                    }
                    
                    //将解压的uoamp-agent-common-0.0.1-SNAPSHOT.jar复制到根目录下并命名为uoamp-agent-common.new.jar
                    String commonSrcFilePath = srcDir.concat("lib/uoamp-agent-common-0.0.1-SNAPSHOT.jar");
                    String commonDstFilePath = dstDir.concat("lib/uoamp-agent-common.new.jar");
                    //如果根目录下有uoamp-agent-common.new.jar则删除
                    File commonFile = new File(commonSrcFilePath);
                    if(commonFile.exists()){
                    	File oldCommonFile = new File(commonDstFilePath);
                    	if(oldCommonFile.exists()){
                    		oldCommonFile.delete();
                    	}
                    	commonCopySuc = WFile.copyFile(commonSrcFilePath, commonDstFilePath);
                    	copysuc = copysuc && commonCopySuc;
                    	Logger.getRootLogger().info("copyFile " + commonSrcFilePath +" result -->".concat(String.valueOf(commonCopySuc)));
                    }
                    
                    //将解压的uoamp-agent-logger-0.0.1-SNAPSHOT.jar复制到根目录下并命名为uoamp-agent-logger.new.jar
                    String loggerSrcFilePath = srcDir.concat("lib/uoamp-agent-logger-0.0.1-SNAPSHOT.jar");
                    String loggerDstFilePath = dstDir.concat("lib/uoamp-agent-logger.new.jar");
                    //如果根目录下有uoamp-agent-logger.new.jar则删除
                    File loggerFile = new File(loggerSrcFilePath);
                    if(loggerFile.exists()){
                    	File oldLoggerFile = new File(loggerDstFilePath);
                    	if(oldLoggerFile.exists()){
                    		oldLoggerFile.delete();
                    	}
                    	loggerCopySuc = WFile.copyFile(loggerSrcFilePath, loggerDstFilePath);
                    	copysuc = copysuc && loggerCopySuc;
                    	Logger.getRootLogger().info("copyFile " + loggerSrcFilePath +" result -->".concat(String.valueOf(loggerCopySuc)));
                    }
                    
        			// 如果jar文件复制成功,接下来复制跟目录下的其他目录和文件
        			if (copysuc) {
        				FileFilter filter = new FileFilter() {
							@Override
							public boolean accept(File pathname) {
								String fileName = pathname.getName();
								boolean isJar = fileName.endsWith(".jar");
								if (!isJar) {
									return true;
								} else {
									// MCAgent-0.0.1-SNAPSHOT.jar是agent的主执行jar,单独进行复制
									return !(fileName.equalsIgnoreCase("uoamp-agent-main-0.0.1-SNAPSHOT.jar") ||
                                             fileName.equalsIgnoreCase("uoamp-agent-core-0.0.1-SNAPSHOT.jar") ||
                                             fileName.equalsIgnoreCase("uoamp-agent-monitor-0.0.1-SNAPSHOT.jar") ||
                                             fileName.equalsIgnoreCase("uoamp-agent-common-0.0.1-SNAPSHOT.jar") ||
                                             fileName.equalsIgnoreCase("uoamp-agent-logger-0.0.1-SNAPSHOT.jar"));
								}
							}
						};
						WFile.copyDirectory(srcDir, dstDir, filter);
					}
        			
        			//如果复制成功，则赋予该jar包执行权限并且执行重启操作，版本更新成功;否则重新把旧版本写入"conf/version"，待下一次更新线程启动时，重新下载新版本的压缩包
        			if(copysuc){
        				if (isLinux) {
        					String execCommand = "chmod 700 -R ".concat(dstDir);
            				try {
            					// 在Lniux环境下，赋予权限
            					Process process = Runtime.getRuntime().exec(execCommand);
            					int rtnCode = process.waitFor();
            					Logger.getRootLogger().info("execute cmd result -->".concat(execCommand).concat(" -->").concat(String.valueOf(rtnCode)));
            				} catch (IOException e) {
            					Logger.getRootLogger().error("execute cmd error -->".concat(execCommand), e);
            				}
						}
        				
        				try {
        					//解压完之后删掉压缩包和解压文件
        					WFile.deleteDirectory(dir + "/upload/agentzip");
						} catch (Exception e) {
							Logger.getRootLogger().error("deleteDirectory error -->".concat(dir + "/upload/agentzip"), e);
						}
        				
        				Logger.getRootLogger().info("try restart....");
        				if (isLinux) {
        					CMDExextor.execut("./redeploy.sh");
        				} else {
        					CMDExextor.execut("./redeploy.bat");
        				}
        			}
        		}
        	}
        	
        	if(!copysuc){
            	//如果该文件夹存在，则需要把它清空，以免后续下载出现文件重名情况
        		String deletePath = dir + "/upload/agentzip";
        		try {
					WFile.deleteDirectory(deletePath);
				} catch (Exception e) {
					Logger.getRootLogger().error("deleteDirectory error : deletePath-->".concat(deletePath), e);
				}
        		
            	//更改"conf/version"为原来的版本号
            	WFile.wf("conf/version",localVersion ,"utf-8",false);	
            }
        	
		} catch (Exception e) {
			Logger.getRootLogger().info("MCAgent更新失败："+e);
		}
	}
}
